﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace ine.Extensions
{
    public static class ColumnsExtensions
    {
        public static void Autofill(this ListView target)
        {
            GridView view = target.View as GridView;

            if (target.ActualWidth == Double.NaN)
                target.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));

            int autoFillColumnIndex = view.Columns.Count - 1;
            double maxWidth = view.Columns.Max(x => x.ActualWidth);

            double remainingSpace = target.ActualWidth;
            for (int i = 0; i < view.Columns.Count; i++)
            {
                if (view.Columns[i].ActualWidth != maxWidth)
                {
                    remainingSpace -= view.Columns[i].ActualWidth;
                }
                else
                {
                    autoFillColumnIndex = i;
                }
            }

            view.Columns[autoFillColumnIndex].Width = remainingSpace - 18 >= 0 ? remainingSpace - 18 : 0;
        }
    }
}
